import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 项目基准地址
  // baseURL: 'http://ihrm-java.itheima.net',
  timeout: 5000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在js文件中获取vuex的值
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.success) {
      return response.data
    } else {
      Message({
        message: response.data.message,
        type: 'error'
      })
      return Promise.reject(new Error(response.data.message))
    }
  },
  error => {
    console.dir(error.response && error.response.data.success, 123)
    if (error.response && error.response.data && error.response.data.code === 10002) {
      console.log(1)
      store.commit('user/removeUserInfoMutations')
      store.commit('user/removeTokenMutations')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
